//package com.ruoyi.activiti.modeler.support;
//
//import org.activiti.bpmn.model.UserTask;
//import org.activiti.engine.delegate.Expression;
//import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
//import org.activiti.engine.impl.persistence.entity.TaskEntity;
//import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
//import org.activiti.engine.impl.task.TaskDefinition;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.util.CollectionUtils;
//import org.springframework.util.StringUtils;
//
//import java.util.*;
//import java.util.stream.Collectors;
//
//public class UserTaskActivityBehaviorSupport extends UserTaskActivityBehavior {
//
//    private static final Logger LOGGER = LoggerFactory.getLogger(UserTaskActivityBehavior.class);
//
//    private ParticipantManager participantManager;
//
//    private UserTask userTask;
//
//    /**
//     * 初始化
//     * 		participantManager：各种解析器[角色、用户、部门、、]
//     */
//    public UserTaskActivityBehaviorSupport(ParticipantManager participantManager, UserTask userTask,
//                                           TaskDefinition taskDefinition) {
//        super(userTask.getId(), taskDefinition);
//        this.participantManager = participantManager;
//        this.userTask = userTask;
//    }
//
//    /**
//     * 当流程开始的活动的时候
//     * 对Task的受托人、候选组、候选用户等Expression进行getValue()的计算，Task的信息保存入库
//     */
//    @Override
//    protected void handleAssignments(Expression assigneeExpression, Expression ownerExpression,
//                                     Set<Expression> candidateUserExpressions, Set<Expression> candidateGroupExpressions, TaskEntity task,
//                                     ActivityExecution execution) {
//        LOGGER.info("####### 进入handleAssignments");
//        List<String> groups = userTask.getCandidateGroups();
//        /**
//         * 解析任务的候选人、多实例
//         */
//        if(userTask.getLoopCharacteristics() != null) {
//            // 从流程变量里拿_orgCode、orgCode、_user
//            Map<String,Object> vars = execution.getVariables(Arrays.asList(Constant.MULTI_INST_TASK_ORG_VAR_NAME,Constant.PROCESS_ORG_CODE_VAR_NAME,Constant.MULTI_INST_COLLECTION_ITEM_VAR_NAME));
//            String orgCode = (String)vars.get(Constant.MULTI_INST_TASK_ORG_VAR_NAME);
//            // 从上下文拿组织编号
//            if(StringUtils.isEmpty(orgCode)) {
//                orgCode = (String)vars.get(Constant.PROCESS_ORG_CODE_VAR_NAME);
//                if(StringUtils.isEmpty(orgCode)) {
//                    orgCode = Context.getCurrentOrganizationCode();
//                }
//            }
//            task.setVariableLocal(Constant.TASK_ORG_CODE_VAR_NAME, orgCode, false);
//            String user = (String)vars.get(Constant.MULTI_INST_COLLECTION_ITEM_VAR_NAME);
//            LOGGER.info("handleTaskAssignments-> processId:{}, taskName:{},taskId:{},user:{}",execution.getProcessInstanceId(), task.getName(), task.getId(), user);
//            // 设置user
//            if(!StringUtils.isEmpty(user)) {
//                LOGGER.info("设置user :" + user);
//                task.addCandidateUser(user);
//            }
//            candidateGroupExpressions = Collections.emptySet();
//        } else if (!CollectionUtils.isEmpty(groups)) {
//            LOGGER.info("handleTaskAssignments-> processId:{}, taskName:{},taskId:{},groups:{}",execution.getProcessInstanceId(), task.getName(), task.getId(), StringUtils.collectionToCommaDelimitedString(groups));
//            Map<String, Object> vars = execution.getVariables(Arrays.asList(Constant.PROCESS_ORG_CODE_VAR_NAME, Constant.PROCESS_DEPT_CODE_VAR_NAME));
//            String orgCode = (String) vars.get(Constant.PROCESS_ORG_CODE_VAR_NAME);
//            String deptCode = (String) vars.get(Constant.PROCESS_DEPT_CODE_VAR_NAME);
//            if (StringUtils.isEmpty(deptCode)) {
//                deptCode = Context.getCurrentDeptCode();
//            }
//            if (StringUtils.isEmpty(orgCode)) {
//                orgCode = Context.getCurrentOrganizationCode();
//            }
//            int userCount = 0;
//            List<Expression> groupExpressionList = new ArrayList<>(candidateGroupExpressions);
//            for (int i= 0 ; i < groups.size(); i++) {
//                String group = groups.get(i);
//                if (StringUtils.isEmpty(group)) {
//                    continue;
//                }
//                if(group.contains("${")) {
//                    Expression expr = groupExpressionList.get(i);
//                    Object value = expr.getValue(execution);
//                    userCount = this.handleCandidateGroup(value, task, execution, orgCode, deptCode);
//                } else {
//                    userCount = this.handleCandidateGroup(group, task, execution, orgCode, deptCode);
//                }
//                if (userCount > 0) {
//                    break;
//                }
//            }
//            candidateGroupExpressions = Collections.emptySet();
//        } else {
//            String orgCode = (String) execution.getVariable(Constant.PROCESS_ORG_CODE_VAR_NAME);
//            task.setVariableLocal(Constant.TASK_ORG_CODE_VAR_NAME, orgCode, false);
//        }
//        super.handleAssignments(assigneeExpression, ownerExpression, candidateUserExpressions, candidateGroupExpressions, task, execution);
//    }
//
//    @SuppressWarnings({ "rawtypes", "unchecked" })
//    private int handleCandidateGroup(Object value, TaskEntity task, ActivityExecution execution, String orgCode, String deptCode) {
//        LOGGER.info("####### 进入handleCandidateGroup");
//        LOGGER.info("handleCandidateGroup-> processId:{}, taskName:{},taskId:{},group Value:{}",execution.getProcessInstanceId(), task.getName(), task.getId(), value);
//        if (StringUtils.isEmpty(value)) {
//            task.setVariableLocal(Constant.TASK_ORG_CODE_VAR_NAME, orgCode, false);
//            return 0;
//        }
//        List<String> groupList = new ArrayList<>(1);
//        if (value instanceof String) {
//            String[] groups = StringUtils.tokenizeToStringArray((String) value, ",");
//            groupList = Arrays.asList(groups);
//        } else if (value instanceof Collection) {
//            groupList.addAll((Collection) value);
//        }
//        if (groupList.isEmpty()) {
//            return 0;
//        }
//        // 第一候选人
//        CandidateGroupInfo groupInfo = Utils.parseCandidateGroupInfo(groupList.get(0));// 把前端的乱码解析成id
//        List<String> users = this.participantManager.resolvePrincipals(groupInfo, orgCode, deptCode);// 根据筛选方式解析出userIds
//        if (!CollectionUtils.isEmpty(users)) {
//            task.addCandidateUsers(users);
//            LOGGER.info("####### 添加第一候选人" + users);
//        } else if (groupList.size() > 1) {
//            // 第二候选人
//            groupInfo = Utils.parseCandidateGroupInfo(groupList.get(1));
//            users = this.participantManager.resolvePrincipals(groupInfo, orgCode, deptCode);
//            task.addCandidateUsers(users);
//            LOGGER.info("####### 添加第二候选人" + users);
//        }
//        if (users == null) {
//            throw new I18nErrorException("workflowPage", "activeNotApproverMsg", "未找到流程配置审批人");
////			users = Collections.emptyList();
//        }
//        LOGGER.info("handleCandidateGroup-> processId:{}, taskName:{},taskId:{},candidateUsers:{}",execution.getProcessInstanceId(), task.getName(), task.getId(), StringUtils.collectionToDelimitedString(users, ","));
//        // 解析任务是否有指定组织
//        String taskOrgCode = this.participantManager.resolveOrgCode(groupInfo);
//        if (StringUtils.isEmpty(taskOrgCode)) {
//            taskOrgCode = orgCode;
//        }
//        task.setVariableLocal(Constant.TASK_ORG_CODE_VAR_NAME, taskOrgCode, false);
//        LOGGER.info("handleCandidateGroup-> processId:{}, taskName:{},taskId:{},orgCode:{}",execution.getProcessInstanceId(), task.getName(), task.getId(), taskOrgCode);
//        //LOGGER.info("Resoved task:{} OrgCode:{} ", task.getId(), taskOrgCode);
//        return users.size();
//    }
//
//    @SuppressWarnings({ "rawtypes", "unchecked" })
//    private int handleCandidateGroup(Object value, ActivityExecution execution, String orgCode, String deptCode) {
//        LOGGER.info("####### 进入private handleCandidateGroup");
//        //LOGGER.info("handle task:{}-{} with CandidateGroup value:{}", userTask.getId(), userTask.getName(), value);
//        LOGGER.info("handleCandidateGroup-> processId:{}, taskName:{},group:{}",execution.getProcessInstanceId(), userTask.getName(), value);
//        if (StringUtils.isEmpty(value)) {
//            return 0;
//        }
//        List<String> groupList = new ArrayList<>(1);
//        if (value instanceof String) {
//            String[] groups = StringUtils.tokenizeToStringArray((String) value, ",");
//            groupList = Arrays.asList(groups);
//        } else if (value instanceof Collection) {
//            groupList.addAll((Collection) value);
//        }
//        if (groupList.isEmpty()) {
//            return 0;
//        }
//        // 第一候选人
//        CandidateGroupInfo groupInfo = Utils.parseCandidateGroupInfo(groupList.get(0));
//        List<String> users = this.participantManager.resolvePrincipals(groupInfo, orgCode, deptCode);/** 解析groupInfo，这里是修改点，通过ROLE_TO_USER:8f4d37e4-c1e6-45dd-b999-99f8e4b0a9b1调用对应的解析器，然后拿到roleId再根据orgCode和roleId查出userInfo */
//        if (!CollectionUtils.isEmpty(users)) {
//            execution.setVariable(Constant.MULTI_INST_COLLECTION_VAR_NAME, processUsers(users));
//            LOGGER.info("########### 设置collectionUsers第一候选人 _users设置" + users);
//        } else if (groupList.size() > 1) {
//            // 第二候选人
//            groupInfo = Utils.parseCandidateGroupInfo(groupList.get(1));
//            users = this.participantManager.resolvePrincipals(groupInfo, orgCode, deptCode);
//            execution.setVariable(Constant.MULTI_INST_COLLECTION_VAR_NAME, processUsers(users));
//            LOGGER.info("########### 设置collectionUsers _users设置第二候选人" + users);
//        }
//        if (users == null) {
//            users = Collections.emptyList();
//        }
//        LOGGER.info("handleCandidateGroup-> processId:{}, taskName:{},candidateUsers:{}",execution.getProcessInstanceId(), userTask.getName(), StringUtils.collectionToDelimitedString(users, ","));
//        // 解析任务是否有指定组织
//        String taskOrgCode = this.participantManager.resolveOrgCode(groupInfo);
//        if (!StringUtils.isEmpty(taskOrgCode)) {
//            execution.setVariable(Constant.MULTI_INST_TASK_ORG_VAR_NAME, taskOrgCode, false);
//        }
//        return users.size();
//    }
//
//    private Object processUsers(List<String> users) {
//        if(users.size() > 50) {
//            return users;
//        }
//        return users.stream().collect(Collectors.joining(","));
//    }
//
//    public void beforeExecuteMultiInstance(ActivityExecution execution) {
//        LOGGER.info("####### 进入beforeExecuteMultiInstance");
//        List<String> groups = userTask.getCandidateGroups();
//        LOGGER.info("beforeExecuteMultiInstance-> processId:{}, taskName:{}, groups:{}", execution.getProcessInstanceId(), userTask.getName(), StringUtils.collectionToCommaDelimitedString(groups));
//        Map<String, Object> vars = execution.getVariables(Arrays.asList(Constant.PROCESS_ORG_CODE_VAR_NAME, Constant.PROCESS_DEPT_CODE_VAR_NAME));
//        String orgCode = (String) vars.get(Constant.PROCESS_ORG_CODE_VAR_NAME);
//        String deptCode = (String) vars.get(Constant.PROCESS_DEPT_CODE_VAR_NAME);
//        if (StringUtils.isEmpty(deptCode)) {
//            deptCode = Context.getCurrentDeptCode();
//        }
//        if (StringUtils.isEmpty(orgCode)) {
//            orgCode = Context.getCurrentOrganizationCode();
//        }
//        for(String group : groups) {
//            int count = this.handleCandidateGroup(group, execution, orgCode, deptCode);
//            if(count > 0) {
//                break;
//            }
//        }
//    }
//}
